import { defineAsyncComponent, markRaw, AsyncComponentLoader } from "vue";
// @ts-ignore
import { loadModule } from "vue3-sfc-loader";
import Loading from "@/component/Loading.vue";
// import

const addStyle = (textContent: string): void => {
  const style = Object.assign(document.createElement("style"), { textContent });
  const ref = document.head.getElementsByTagName("style")[0] || null;
  // @ts-ignore
  document.head.insertBefore(style, ref);
};

const loadMarkRawComponent = (file: string, options: any = {}) => {
  const moduleOptions: any = {
    moduleCache: {
      vue: window.Vue,
      // "vue-i18n": window.VueI18n,
      // "@opentiny/vue": TinyVue,
    },
    addStyle,
    ...options,
  };
  const Loader: AsyncComponentLoader = () => loadModule(file, moduleOptions);
  return markRaw(
    defineAsyncComponent({
      loader: Loader,
      loadingComponent: Loading,
      delay: 200,
      timeout: 10000,
    }),
  );
};

/**
 * @param fileName
 * @param content
 */
export const loadFileComponent = (fileName: string, content: string) => {
  return loadMarkRawComponent(fileName, {
    async getFile() {
      return {
        getContentData: () => Promise.resolve(content),
      };
    },
  });
};

/**
 *
 * @param file
 */
export const loadApiComponent = (file: string) => {
  return loadMarkRawComponent(file, {
    async getFile(_apiUrl: string) {
      const content = ""; //await request.get(apiUrl);

      return {
        getContentData: () => Promise.resolve(content),
      };
    },
  });
};

/**
 * { path:string, tpl:string }
 * @param item
 */
export const loadSfcComponent = (item: { path: string; tpl: string }) => {
  return loadFileComponent(item.path, item.tpl);
};
